﻿using System;
using System.Collections.Generic;
using System.Linq;
using System.Text;
using System.Net.Sockets;
using System.Net;
using System.Text.RegularExpressions;
using System.Threading;

namespace WebSocket
{
    public class WebSocketClient
    {
        public WebSocketClient(string host, int port)
        {
            host = host.ToLower();
            if (!host.StartsWith("ws://") && !host.StartsWith("wss://"))
            {
                throw new ArgumentException("the host must start with ws:// or wss://");
            }
            this.Connect(host, port);
        }


        public event CloseEventHandler OnClose;

        public event OpenEventHandler OnOpen;

        public event MessageEventHandler OnMessage;

        public event ErrorEventHandler OnError;

        private HandShake handShake;

        private Socket socket;

        public ReadyState ReadyState { get; private set; }

        public long BufferedAmount { get; private set; }

        private void Connect(string host, int port)
        {
            this.ReadyState = ReadyState.CONNECTING;

            if (host.EndsWith("/"))
            {
                host = host.Remove(host.Length - 1);
            }

            this.socket = new Socket(AddressFamily.InterNetwork, SocketType.Stream, ProtocolType.Tcp);
            this.socket.Connect(host.Substring(host.IndexOf("//") + 2), port);
            this.handShake = new HandShake(host + ":" + port, this.socket.LocalEndPoint.ToString());
            this.socket.Send(this.handShake.OpenHandShake());

            // handshake bytes from server
            byte[] hsBytes = new byte[1024];
            int length = this.socket.Receive(hsBytes);

            Regex connRegex = new Regex(@"Connection:\s?(?<Connection>\w+)");
            Regex upgradeRegex = new Regex(@"Upgrade:\s?(?<Upgrade>\w+)");
            Regex secWebSocketOriginRegex = new Regex(@"Sec-WebSocket-Origin:\s?(?<SecWebSocketOrigin>[\d\w\/\:\.]+)");
            Regex secWebSocketLocationRegex = new Regex(@"Sec\-WebSocket\-Location:\s?(?<SecWebSocketLocation>[\d\w\/\:\.]+)");
            Regex secWebSocketProtocolRegex = new Regex(@"Sec\-WebSocket\-Protocol:\s?(?<SecWebSocketProtocol>[\d\w\/\:\.]+)");


            string resource = Encoding.UTF8.GetString(hsBytes);
            string upgrade = upgradeRegex.Match(resource).Groups["Upgrade"].Value;
            string connection = connRegex.Match(resource).Groups["Connection"].Value;
            string origin = secWebSocketOriginRegex.Match(resource).Groups["SecWebSocketOrigin"].Value;
            string location = secWebSocketLocationRegex.Match(resource).Groups["SecWebSocketLocation"].Value;

            GroupCollection gc = secWebSocketProtocolRegex.Match(resource).Groups;
            if (gc.Count > 0)
            {
                string protocol = gc["SecWebSocketProtocol"].Value;
            }

            byte[] targetBytes = this.handShake.GetComputedBytes();

            for (int cnt = 0; cnt < 16; cnt++)
            {
                if (targetBytes[targetBytes.Length - 16 + cnt] != hsBytes[length - 16 + cnt])
                {
                    if (this.OnClose != null)
                    {
                        this.OnClose();
                    }
                }
            }

            // validation received bytes
            if (!connection.Equals(this.handShake.Connection))
            {
                throw new ApplicationException("Connection error." + connection + "!=" + this.handShake.Connection);
            }

            string allHost = this.handShake.IsWSS ? "wss://" : "ws://" + this.handShake.Host + "/";
            if (!location.Equals(allHost))
            {
                throw new ApplicationException("Sec-WebSocket-Location error." + location + "!=" + allHost);
            }

            if (!origin.Equals(this.handShake.Origin))
            {
                throw new ApplicationException("Sec-WebSocket-Origin error." + origin + "!=" + this.handShake.Origin);
            }

            this.ReadyState = ReadyState.OPEN;

            if (this.OnOpen != null)
            {
                this.OnOpen();
            }

            new Thread(delegate()
            {
                while (true)
                {
                    if (this.ReadyState == ReadyState.CLOSED)
                    {
                        break;
                    }
                    byte[] dataBytes = new byte[1024];
                    int dataLength = this.socket.Receive(dataBytes);
                    Array.Resize(ref dataBytes, dataLength);
                    this.OnMessage(this.socket, dataBytes);
                }
            }).Start();
        }

        public void Send(string data)
        {
            if (this.ReadyState == ReadyState.OPEN)
            {
                byte[] dataBytes = Encoding.UTF8.GetBytes(data);
                byte[] sendBytes = new byte[dataBytes.Length];

                sendBytes[0] = 0x00;
                sendBytes[dataBytes.Length + 1] = 0xFF;
                Array.Copy(dataBytes, 0, sendBytes, 1, dataBytes.Length);

                this.socket.Send(sendBytes);
            }
        }

        public void Close()
        {
            this.ReadyState = ReadyState.CLOSED;
            this.socket.Close();
        }
    }
}
